<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\Area;
use app\models\Brand;
use app\models\BrandButler;
use app\models\Category;
use app\models\Channel;
use app\models\ContactForm;
use app\models\LoginForm;
use app\models\JoinNum;
use app\models\Article;
use yii\helpers\Url;

class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }
    private $http_type,$http_domain;
    public function init()
    {
        $this->http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https' : 'http';
        $this->http_domain = str_replace(explode('.', $_SERVER['SERVER_NAME'])[0], '', $_SERVER['SERVER_NAME']);
        return true;
    }
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            // 'error' => [
            //     'class' => 'yii\web\ErrorAction',
            // ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionError()
    {
        $exception = Yii::$app->errorHandler->exception;
        if ($exception !== null) {
            $is_wap = $this->isWap();
            if ($is_wap && !strstr($controller_id, 'wap')) {//wap环境访问非wap页面,需要重定向到wap页面路由
                return $this->renderpartial('wap-error');
            } else {
                return $this->renderpartial('error');
            }
        }
    }

    private function isWap(){
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备
        if (isset ($_SERVER['HTTP_VIA']))
        {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
                );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }
    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->renderpartial('index');
    }

    public function actionMap()
    {
        $cate_data = Category::getList();
        $province_id = 0;
        $city_name = $this->getCity();
        $city_info = Area::find()->where(['name' => $city_name, 'level' => 1])->one();
        if ($city_info) {
            $province_id = $city_info->parentArea->id;
        }
        $province_list = Area::find()->where(['level' => 0])->all();
        $city_list = Area::find()->where(['parent_id' => $city_info->parentArea->id, 'level' => 1])->all();
        $area_list = Area::find()->where(['parent_id' => $city_info->id, 'level' => 2])->andWhere("name <> '市辖区'")->all();
        $channel_list = Channel::find()->where(['type' => [1,3], 'status' => 1])->all();
        $gj_info = BrandButler::find()->where(['status' => 1])->orderBy('join_num desc')->one();
        $join_num = JoinNum::findOne(1);
        $join_num->join_num_today = $this->getJoinNum($join_num->join_num_today);
        $data = [
            'http_type' => $this->http_type,
            'http_domain' => $this->http_domain,
            'province_id' => $province_id,
            'city_id' => $city_info->id,
            'cate_list' => $cate_data,
            'province_list' => $province_list,
            'city_list' => $city_list,
            'area_list' => $area_list,
            'channel_list' => $channel_list,
            'gj_info' => $gj_info,
            'join_num' => $join_num,
        ];
        // var_dump($cate_data);
        // exit;
        return $this->renderpartial('map', $data);
    }

    private function getJoinNum($join_num_today) {
        if ($join_num_today < 10) {
            return "000" . $join_num_today;
        } else if ($join_num_today < 100) {
            return "00" . $join_num_today;
        } else if ($join_num_today < 1000) {
            return "0" . $join_num_today;
        }
        return (string)$join_num_today;
    }
    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return Response|string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    /**
     * Displays about page.
     *
     * @return string
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    private function getCity() {
        $env = Yii::$app->params['env'];
        if ($env == 'dev') {//本地环境
            $ip = file_get_contents('http://pv.sohu.com/cityjson?ie=utf-8');
            preg_match('/{.+}/i', $ip, $m);
            $array = json_decode($m[0]);
            $ip = $array->cip;
        } else {
            if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
                $cip = $_SERVER["HTTP_CLIENT_IP"];
            } else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (!empty($_SERVER["REMOTE_ADDR"])) {
                $cip = $_SERVER["REMOTE_ADDR"];
            } else {
                $cip = '';
            }
            preg_match("/[\d\.]{7,15}/", $cip, $cips);
            $ip = isset($cips[0]) ? $cips[0] : 'unknown';
            unset($cips);
        }
        //echo $ip;die;
        //$url = 'http://whois.pconline.com.cn/ipJson.jsp?callback=testJson&ip='.$ip;
        //$ak = '自己的ak值';
        //$ip = "112.21.162.59";
        $url = "http://api.map.baidu.com/location/ip?ip=".$ip."&ak=pDdi7AY3999O01bmMTRMViB6";
        @file_get_contents($url);
        $http_code = $http_response_header[0];
        if(strpos($http_code,'200 OK') !== false){
            $result = file_get_contents($url); //调用接口获取信息
            $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换，否则乱码
            $result = json_decode($result,true);
            $city_name = $result['content']['address_detail']['city'];
            return $city_name;
        }
    }
}
